const API_URL = "/api/file-upload";

const processResponse = async (response: Response) => {
    try {
        const responseJSON = await response.json();
        return responseJSON;
    } catch (error) {
        return {
            success: false
        };
    }
};

/*------------------------------------------------------*/
/* 开启上传会话 */

/**
 * SessionInitialRes
 */
export interface SessionInitialRes {
    /**
     * 会话ID，唯一会话ID
     */
    sessionID: string;
    /**
     * 成功，成功标签
     */
    success: boolean;
}

const startUploadSessionURL = API_URL + "/initial-session";
export async function startUploadSession(): Promise<SessionInitialRes> {
    const response = await fetch(startUploadSessionURL, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        }
    });
    return processResponse(response);
}

/*------------------------------------------------------*/
/* 上传文件切片 */

/**
 * FileUploadSubmitChunkRes
 */
export interface FileUploadSubmitChunkRes {
    /**
     * 块索引，文件块索引
     */
    chunkIndex: string;
    /**
     * 会话ID，唯一会话ID
     */
    sessionID: string;
    /**
     * 成功，成功标签
     */
    success: boolean;
}

const uploadFileChunkURL = API_URL + "/submit-chunk";
export async function uploadFileChunk(
    chunkData: Blob,
    sessionID: string,
    algorithm: string,
    chunkHash: string,
    chunkIndex: string
): Promise<FileUploadSubmitChunkRes> {
    const response = await fetch(uploadFileChunkURL, {
        method: "POST",
        headers: {
            "Content-Type": "application/octet-stream",
            "Session-ID": sessionID,
            "Chunk-hash": chunkHash,
            Algorithm: algorithm,
            "Chunk-Index": chunkIndex
        },
        body: chunkData
    });
    return processResponse(response);
}

/*------------------------------------------------------*/
/* 完成文件上传 */

export interface CompleteFileUploadParams {
    sessionID: string;
    name: string;
    suffix: string;
    describe?: string;
}

/**
 * FileUploadCompleteRes
 */
export interface FileUploadCompleteRes {
    /**
     * 会话ID，唯一会话ID
     */
    sessionID: string;
    /**
     * 成功，成功判据
     */
    success: boolean;
}

const completeFileUploadURL = API_URL + "/complete-upload";
export async function completeFileUpload(
    params: CompleteFileUploadParams
): Promise<FileUploadCompleteRes> {
    const response = await fetch(completeFileUploadURL, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(params)
    });
    return processResponse(response);
}

/*------------------------------------------------------*/
/* 结束上传会话 */

/**
 * SessionFinishRes
 */
export interface SessionFinishRes {
    /**
     * 会话ID，唯一会话ID
     */
    sessionID: string;
}

const finishUploadSessionURL = API_URL + "/finish-session";
export async function finishUploadSession(sessionID: string): Promise<SessionFinishRes> {
    const response = await fetch(finishUploadSessionURL, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({ sessionID })
    });
    return processResponse(response);
}
